<html>
<head>

<title>Groovy Goodness: Use a Class by Proxy</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Use a Class by Proxy</h3>

<div class="post">
<p>In the <code>groovy.util</code> package we find the <code>Proxy</code> class. We can use this class to create a proxy for another object. All methods calls to the proxy object are redirected to the original object, instead for the methods we override in the proxy class:</p>
<pre class="brush:groovy">
class User {
    String name
    String email
    String password

    String displayName() { name }
}

class UserProxy extends groovy.util.Proxy {
    List fields

    // Override getProperty for custom behavior by the proxy.
    Object getProperty(String propertyName) {
        if (propertyName in fields) {
            getAdaptee().getProperty(propertyName)
        } else {
            throw new MissingPropertyException("Unknown property $propertyName")
        }
    }
}

def user = new User(name: 'mrhaki', email: 'private@localhost', password: 'secret')
def userProxy= new UserProxy(fields: ['name']).wrap(user)  // Create proxy for user instance.

assert 'mrhaki' == userProxy.name
try {
    userProxy.email
    assert false
} catch (MissingPropertyException e) {
    assert 'Unknown property email' == e.message
}
assert 'mrhaki' == userProxy.displayName()  // Use original method.
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>